package org.nyt.medicalstore.service.impl;

import org.apache.coyote.BadRequestException;
import org.nyt.medicalstore.model.Drug;
import org.nyt.medicalstore.model.Symptom;
import org.nyt.medicalstore.model.SymptomDrugRelation;
import org.nyt.medicalstore.repository.DrugRepository;
import org.nyt.medicalstore.repository.SymptomDrugRelationRepository;
import org.nyt.medicalstore.repository.SymptomRepository;
import org.nyt.medicalstore.service.SymptomDrugRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class SymptomDrugRelationServiceImpl implements SymptomDrugRelationService {
    @Autowired
    private SymptomRepository symptomRepository;
    @Autowired
    private SymptomDrugRelationRepository symptomDrugRelationRepository;
    @Autowired
    private DrugRepository drugRepository;



    @Override
    public List<Drug> getRelatedDrugs(Long symptomId) {
        return symptomRepository.findRelatedDrugs(symptomId);

    }

    @Override
    public SymptomDrugRelation addSymptomDrugRelation(Long symptomId, Long drugId, Double confidence) throws BadRequestException {
        Symptom symptom = symptomRepository.findById(symptomId).orElse(null);
        Drug drug = drugRepository.findById(drugId).orElse(null);
        if (symptom == null || drug == null) {
            throw new BadRequestException("symptom or drug is null");
        }
        Optional<SymptomDrugRelation> existing = symptomDrugRelationRepository.findBySymptomAndDrug(symptomId, drugId);
        if (existing.isPresent()) {
            throw new BadRequestException("Relation already exists between symptom and drug");
        }
        SymptomDrugRelation relation = new SymptomDrugRelation();
        relation.setSymptom(symptom);
        relation.setDrug(drug);
        relation.setConfidence(confidence);
        return symptomDrugRelationRepository.save(relation);
    }

    @Override
    public void deleteSymptomDrugRelation(Long symptomId, Long drugId) throws BadRequestException {
        Symptom symptom = symptomRepository.findById(symptomId).orElse(null);
        Drug drug = drugRepository.findById(drugId).orElse(null);
        if (symptom == null || drug == null) {
            throw new BadRequestException("symptom or drug is null");
        }
        Optional<SymptomDrugRelation> existing = symptomDrugRelationRepository.findBySymptomAndDrug(symptomId, drugId);
        if (existing.isPresent()) {
            symptomDrugRelationRepository.deleteBySymptomAndDrug(symptomId,drugId);
        }else {
            throw new BadRequestException("Relation not exists between symptom and drug");
        }
    }
}
